﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using Model;
using System.Configuration;
using Indigox.SSO.Client;
using Newtonsoft.Json;

namespace WebApplication.AppCode
{
    public class BasePage : Page
    {
        private UserInfo currentUser = null;
        protected UserInfo CurrentUser { get { return currentUser; } }

        protected override void OnPreInit(EventArgs e)
        {
            if (CurrentUser == null)
            {
                if (HttpContext.Current.Session["UserInfo"] != null)
                {
                    currentUser = (UserInfo)HttpContext.Current.Session["UserInfo"];
                }
                else if (HttpContext.Current.Request.Cookies["UserInfo"] != null)
                {
                    var cookieString = HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["UserInfo"].Value);
                    cookieString = Tools.Decrypt(cookieString);
                    currentUser = JsonConvert.DeserializeObject<UserInfo>(cookieString);
                    HttpContext.Current.Session["UserInfo"] = currentUser;
                }
                else
                {
                    Response.Redirect("~/Login.aspx?url=" + this.Request.Url.PathAndQuery);
                }
            }
            base.OnPreInit(e);
        }



        protected void RegisterScript(string script)
        {
            ScriptManager.RegisterClientScriptBlock(this, typeof(string), Guid.NewGuid().ToString(), "$(function(){" + script + "});", true);
        }



        private void CheckPermission()
        {

        }

        protected void Alert(string message)
        {
            ScriptManager.RegisterClientScriptBlock(this, typeof(string), Guid.NewGuid().ToString(), "$(function(){mini.alert('" + message + "');});", true);
        }

        protected void TimeAlert(string message)
        {
            ScriptManager.RegisterClientScriptBlock(this, typeof(string), Guid.NewGuid().ToString(), "$(function(){notify('" + message + "');});", true);
        }

        internal void AlertDataNotFound()
        {
            Alert("未找到数据");
        }

        internal void AlertArgmentInvalid()
        {
            Alert("参数错误！");
        }

        internal void AlertOperateFailed(string poperation, Exception ex)
        {
            Alert(poperation + "数据时出错，请重试或联系管理员！");
        }

        internal void TimeAlertSuccess()
        {
            TimeAlert("操作成功！");
        }

        internal void CloseWindow()
        {
            ScriptManager.RegisterClientScriptBlock(this, typeof(string), Guid.NewGuid().ToString(), "while(!window.CloseOwnerWindow);CloseWindow('ok');", true);
        }
    }
}